<?php
/**
 * Created by PhpStorm.
 * User: Inhere
 * Date: 14-4-1
 * Time: 上午10:08
 */
namespace ulue\web;

use Ulue;
use ulue\core\controller\AbstractWebController;

class Controller extends AbstractWebController
{

    public $menu            = array();   //导航栏数据
    public $breadcrumbs     = array();    //面包屑导航
    public $pageTitle       = '';

    protected function _theErrorAction()
    {
        $this->pageTitle .= ' - 404 page !';
        $view_file         = Ulue::$app->get('pages.error_404');
        if ( is_file($view_file) )
        {
            return $this->display($view_file);
        }

        return parent::_theErrorAction($view_file);
    }

    /**
     * 解析数组方式定义的菜单数组
     * rule 1 每一个菜单项定义如下:
     *  'aliasName' =>'nameValue,urlValue',
     *  'aliasName:son' =>array() //有子菜单
     * rule 2 每一个菜单项定义如下:
     *  array(aliasName,'nameValue,urlValue',array()),
     * rule 解析后:
     *  array( aliasName =>array(
     *              'name'=> nameValue,
     *              'url' => urlValue,
     *              'son'=>array() )
     *  ),
     * @param $arr
     * @param array $menus
     * @return array
     */
    static public function ParseArrMenu($arr,$menus=array())
    {
        if ( isset($arr[0]) ){//rule 2
            foreach($arr as $value){
                $key             = trim($value[0]);
                $valueStr        = trim($value[1]);
                list($name,$url) = explode(',',$valueStr);

                $menus[$key] = array(
                    'name'      => $name,
                    'url'       => $url,
                );

                if (isset($value[2])){//有子菜单
                    $menus[$value[0]]['son'] = self::ParseArrMenu( $value[2] );
                }
            }
        }
        else {//rule 1
            foreach($arr as $key=>$value){
                $key = trim($key);

                if (is_string($value)){
                    $value           = trim($value);
                    list($name,$url) = explode(',',$value);
                    $menus[$key]     = array(
                        'name'          => $name,
                        'url'           => $url,
                    );
                }
                if (isset($arr[$key.':son'])){//有子菜单
                    $menus[$key]['son'] = self::ParseArrMenu( $arr[$key.':son'] );
                }
            }
        }

        return $menus;
    }

    /**
     * 输出信息
     * @param  array $infoData
     *  array(
     *   'stateCode'=> $stateCode , 状态 0 失败 1 成功
     *   'message'  => $message,    提示信息
     *   'data'     => $data        若需要，返回数据
     *   'referer'  => $referer     回退地址
     *   );
     *  注：用于错误提示信息时('msg'=> $message)
     *  1. 开启APP_DEBUG时，输出原样的$message,并且附带有跟踪信息.
     *  2. 关闭APP_DEBUG时，默认输出 @internal $defaultMsg;
     *    但当$message含有字符 show: 时，则仍会输出$message.
     * @param  boolean|null $outJson 若不设置，当请求是Ajax时，默认返回 json 格式数据]
     * @return void [type]            [description]
     */
   static public function output(array $infoData,$outJson=NULL)
   {
        $isAjaxRequest    = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest';

        # 无key值，按默认顺序 'stateCode','msg','data'
        if (isset($infoData[0])) {
          $stateCode    = $infoData[0];
          $message      = isset($infoData[1]) ? $infoData[1] : '';
          $data         = isset($infoData[2]) ? $infoData[2] : '';
          $infoData     = array('stateCode'=>$stateCode , 'msg' => $message, 'data' => $data);
        }

        $outJson==NULL && $outJson = $isAjaxRequest ? TRUE:FALSE;

        if ($outJson) {
          \Ulue::quit(json_encode($infoData));
        }

        $urlReferer = isset($_SERVER['HTTP_REFERER'])?$_SERVER['HTTP_REFERER']:null;
        $urlReferer=='' && $urlReferer  = siteUrl();

        @extract($infoData);
        !empty($referer) && $urlReferer = $referer;

        # error info
        if ($stateCode == 0) {
            # APP_DEBUG==true 带有跟踪信息.
            if (APP_DEBUG) {
                $debug_trace = debug_backtrace();
                $errorFile   = $debug_trace[0]['file'] =='' ? 'Unknown' : $debug_trace[0]['file'];
                $errorLine   = $debug_trace[0]['line'] =='' ? 'Unknown' : $debug_trace[0]['line'];
                $errorClass  = $debug_trace[1]['class'] =='' ? '' : $debug_trace[1]['class'].'::';
                $errorFunc   = $debug_trace[1]['function'] =='' ? 'Unknown' : $debug_trace[1]['function'].'()';
                $message     = strpos($message,'show:')!==false ? str_replace('show:', '', $message) : $message;
                $outMsg      = <<<EOF
  <div style="margin:80px auto; width:800px;height:180px;font-family: Menlo, Monaco, Consolas, monospace;">

  <p style="line-height:1.4;">
  <span style="color:#888;">错误　信息：</span><strong>$message </strong> <br>
  <span style="color:#888;">所在的文件：</span>$errorFile <br>
  <span style="color:#888;">错误报告行：</span>第 <strong>$errorLine </strong>行<br>
  <span style="color:#888;">函数(方法)：</span>$errorClass$errorFunc <br>
  <p>
  <a href="$urlReferer"> 返 回 </a>
  </div>
EOF;
            } else {
                // var_dump(strpos($message,'show:')!==false, $message);
                $defaultMsg= '发生错误啦！请重试或报告问题。';
                $message       = strpos($message,'show:')!==false ? str_replace('show:', '', $message) : $defaultMsg;
                $outMsg    =  <<<EOF
<h2 style="margin:100px auto; width:800px;text-align:center;">
<br><span style="font-size:40px;">:( </span>. $message
<p><a href="$urlReferer" style="font-size:14px;"> 返 回 </a></p></h2>
<script>setTimeout(function(){window.location='$urlReferer'},2100);</script>
EOF;
            }
        }# 成功提示
        else {
          $defaultMsg= '操作成功，页面即将跳转！！';
          $message   = !empty($message) ? $message : $defaultMsg;
          $outMsg    =  <<<EOF
<h2 style="margin:100px auto; width:800px;text-align:center;">
<br><span style="font-size:40px;">:) </span>. $message
<p><a href="$urlReferer" style="font-size:14px;"> 立即跳转 </a></p></h2>
<script>setTimeout(function(){window.location='$urlReferer'},2100);</script>
EOF;
        }
        \Ulue::quit($outMsg);

    }

}